//
//  CNStatusViewModel.swift
//  Ccweibo
//
//  Created by 陈锦聪 on 16/3/25.
//  Copyright © 2016年 Coco. All rights reserved.
//

import UIKit
import SDWebImage

class CNStatusViewModel: NSObject {

    static let sharedInstance: CNStatusViewModel = CNStatusViewModel()
    
    private var isLoading: Bool = false
    
    private override init() {
        super.init()
        
    }
    
    func loadStatuses(since_id: Int64, max_id: Int64, completion: (statuses: [CNStatus]?, error: NSError?) -> ()) {
        
        if isLoading {
            CNPrint(item: "网络繁忙,请稍后再试")
            let error = NSError(domain: "NetworkBusy", code: -1, userInfo: ["ERROR" : "MULTI-REQUEST"])
            completion(statuses: nil, error: error)
            return
        }
        isLoading = true
        CNStatusDAL.sharedDAL.dalLoadStatus(since_id, max_id: max_id) { (statuses, error) -> () in
            self.isLoading = false
            if error != nil {
                completion(statuses: nil, error: error)
                return
            }
            var status = [CNStatus]()
            // 字典转模型
            for dict in statuses! {
                status.append(CNStatus(dict: dict))
            }
            // 先下载图片,再通知控制器显示微博内容
            self.cacheWebImage(status, completion: completion)
        }
//        let urlString = "2/statuses/home_timeline.json"
//        
//        var parameters = [String: AnyObject]()
//        // 每次加载10条数据
//        parameters["count"] = 10
//       
//        if since_id > 0 { // 需要下拉刷新
//            parameters["since_id"] = NSNumber(longLong: since_id)
//        } else if max_id > 0 { // 需要上拉加载更多
//            parameters["max_id"] = NSNumber(longLong: max_id - 1)
//        }
//        CNPrint(item: "\(parameters)")
        // 测试加载本地数据
//        CNStatusDAL.sharedDAL.loadStatus(since_id, max_id: max_id)
        
//        CNNetworkTool.sharedInstance.sendGetRequest(urlString, parameters: parameters) { (result, error) -> () in
//            
//            self.isLoading = false
//            
//            if error != nil {
////                CNPrint(item: "获取微博数据出错: \(error)")
//                completion(statuses: nil, error: error)
//            } else {
//                // 取出微博数据
//                let data = result?["statuses"] as? [[String: AnyObject]]
//                
//                // 测试保存微博数据到本地
////                CNStatusDAL.sharedDAL.saveStatus(data!)
//                
//                var statuses = [CNStatus]()
//                // 字典转模型
//                for dict in data! {
//                    statuses.append(CNStatus(dict: dict))
//                }
////                CNPrint(item: "微博模型: \(statuses)")
//                // 先下载图片,再通知控制器显示微博内容
//                self.cacheWebImage(statuses, completion: completion)
//                // 通知控制器显示微博内容
////                completion(statuses: statuses, error: nil)
//            }
//        }
    }
    /// 发布微博
    func sendStatus(status: String, image: UIImage?, completion: ((error: NSError?) -> ())) {
        guard let access_token = CNUserAccountViewModel.sharedInstance.userAccount?.access_token else {
            let error = CNNetWorkError.EmptyAccessToken.error()
            completion(error: error)
            return
        }
        let parameters = [
            "access_token": access_token,
            "status": status
        ]
        if image == nil {
            let urlString = "2/statuses/update.json"
            CNNetworkTool.sharedInstance.sendPostRequest(urlString, parameters: parameters) { (_, error) -> () in
                completion(error: error)
            }
        } else {
            let urlString = "2/statuses/upload.json"
            let data = UIImagePNGRepresentation(image!)!
            CNNetworkTool.sharedInstance.sendPostRequest(urlString, parameters: parameters, constructingBodyWithBlock: { (formdata) -> Void in
                formdata.appendPartWithFileData(data, name: "pic", fileName: "x.png", mimeType: "image/png")
                }, completion: { (_, error) -> () in
                    completion(error: error)
            })
        }
    }
    /// 转发/评论微博
    func reposeStatus(id: Int64, status: String?, comment: String?, completion: ((error: NSError?) -> ())) {
        guard let access_token = CNUserAccountViewModel.sharedInstance.userAccount?.access_token else {
            let error = CNNetWorkError.EmptyAccessToken.error()
            completion(error: error)
            return
        }
        var urlString = ""
        var parameters = [
            "access_token": access_token,
            "id": NSNumber(longLong: id)
        ]
        if comment != nil { // 评论微博
            parameters["comment"] = comment
            urlString = "2/comments/create.json"
        } else { // 转发微博
            if status != nil {
                parameters["status"] = status
            }
            urlString = "2/statuses/repost.json"
        }
        CNNetworkTool.sharedInstance.sendPostRequest(urlString, parameters: parameters) { (_, error) -> () in
            completion(error: error)
        }
    }
    private func cacheWebImage(statuses: [CNStatus], completion: (statuses: [CNStatus]?, error: NSError?) -> ()) {
        
        let group = dispatch_group_create()
        
        for status in statuses {
            var downloadURLs = status.pictureURLs
            if downloadURLs == nil {
                downloadURLs = status.retweeted_status?.pictureURLs
            }
            if downloadURLs == nil {
                continue
            }
//            for url in downloadURLs!
            // 单张图片下载后再显示
            if downloadURLs?.count == 1 {
                
                let url = downloadURLs![0]
                // 在异步任务执行之前进入组
                dispatch_group_enter(group)
                SDWebImageManager.sharedManager().downloadImageWithURL(url, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (image, error, _, _, _) -> Void in
                    // 在异步任务执行完成后离出组
                    dispatch_group_leave(group)
                    if error != nil {
                        CNPrint(item: "SDWebImageManager下载图片出错: \(url)")
                        return
                    }
//                    CNPrint(item: "单图下载成功")
                })
            }
        }
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
//            CNPrint(item: "全部完成")
            completion(statuses: statuses, error: nil)
        }
    }
}
